/* 
 * Modbus app for RTU.
 * Copyright (c) 2012  apleilx
 * All rights reserved.
 * no limite
 */

/* ----------------------- Platform includes --------------------------------*/
#define _MAPP_MODULE_
#include "mbapp.h"
#include "os_obj.h" // RTOS object definitions
#include "sys_task.h"
#include "common.h"

#define TEST_MODE MB_RTU_SLAVE

mb_baud_tab_create;

uint8_t mbTestErrCnt = 0;
uint8_t mbTestOkCnt = 0;

typedef struct
{
	uint16_t pv_r[64];
	uint16_t pv_w[64];
	uint16_t obj_size;
} mb_tst_type;

mb_tst_type mb_tst;

void rcv_end_handle_comp(uint8_t ErrSt);

/******************************************************************************
* @brief   	Slave device handle.
*               
* @param   none
*
* @return  none
*
* @ Pass/ Fail criteria: none
*****************************************************************************/
void modbus_task(const void *argv)
{
	mb_cmd_buff_type mcmd;

	//mb_obj_init(&mb.obj08);

	//slave config
	//mb08_Init(MB_RTU_SLAVE, mb_baud_tab[MB_BAUD_115200], MB_PAR_NONE);
	//mb.obj08.slave_id = 1;
	//mb.obj08.os_event_send = mb_os_send;
	//mb.obj08.os_event_base = 1 << 4;
	//mb.obj08.rtu_len_cut = 1;

	mb_obj_init(&mb.obj02);

	//master config
	mb02_Init(MB_RTU_SLAVE, mb_baud_tab[MB_BAUD_115200], MB_PAR_NONE);
	mb.obj02.slave_id = 1;
	mb.obj02.rtu_master_delay_set = 3;
	mb.obj02.rcv_end_handle_comp = rcv_end_handle_comp;
	mb.obj02.os_event_send = mb_os_send;
	mb.obj02.os_event_base = 2 << 4;
	mb.obj02.rtu_len_cut = 1;

	//cmd config
	mcmd.device_id = 0;
	mcmd.cmd = FUN_CODE_READ_COILS;
	mcmd.dat = mb_tst.pv_w;
	mcmd.dat_addr = 0;
	mcmd.amount = 48;
	mcmd.call_back = 0;
	mb.obj02.api->stc_cmd_req(0, &mcmd);

	mcmd.cmd = FUN_CODE_READ_DISCRETE;
	mb.obj02.api->stc_cmd_req(1, &mcmd);

	mcmd.cmd = FUN_CODE_W_R_MULTIPLE_REG;
	mb.obj02.api->stc_cmd_req(2, &mcmd);

	mcmd.cmd = FUN_CODE_W_R_MULTIPLE_REG;
	mb.obj02.api->stc_cmd_req(3, &mcmd);

	mcmd.cmd = FUN_CODE_WRITE_MULTIPLE_REG;
	mb.obj02.api->stc_cmd_req(4, &mcmd);

	mcmd.cmd = FUN_CODE_WRITE_MULTIPLE_COIL;
	mb_tst.pv_w[0] = 0;
	mb.obj02.api->stc_cmd_req(5, &mcmd);

	//task handle
	for (;;)
	{
		ULONG event[2];
		UINT os_err;

		// wait modbus event
		tx_event_flags_get(os_obj.eid_mb, UINT16_MAX, TX_OR_CLEAR, event, ms_ticks(2000));
		//os_api_exe_check();
		
		(void)event;
		
		//mb_poll(&mb.obj08);

		mb_poll(&mb.obj02);

		mb_tst.obj_size = sizeof(mb.obj02);
	}
}

void rcv_end_handle_comp(uint8_t ErrSt)
{
}
